/**
 *  var crtTime = new Date(value);
 *  return top.dateFtt(crtTime,"yyyy-MM-dd hh:mm:ss");   
 */
Vue.filter('date',function(timestamp,fmt){
	var date = new Date(timestamp*1000);
	var o = {   
		"M+" : date.getMonth()+1,                 //月份   
		"d+" : date.getDate(),                    //日   
		"h+" : date.getHours(),                   //小时   
		"m+" : date.getMinutes(),                 //分   
		"s+" : date.getSeconds(),                 //秒   
		"q+" : Math.floor((date.getMonth()+3)/3), //季度   
		"S"  : date.getMilliseconds()             //毫秒   
	};
	if(/(y+)/.test(fmt)){
		fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
	}
	for(var k in o){
		if(new RegExp("("+ k +")").test(fmt)){
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
		}
	}
	return fmt;
});

Vue.filter('route',function(url,param){
	return $_URLROUTE(url,param);
});

Vue.filter('avatarUrl',function(val,sex){
	var sexMap = {
		'sex1':'male/-__('+val+').jpg',
		'sex2':'female/+__('+val+').jpg'
	};
	return window.location.protocol+'//'+window.location.hostname+'/static/avatar/'+sexMap['sex'+sex];
});

var VueListMixin = {
	data : function(){
		var d = {};
		// 排序字段query规则： order[]=field{order_split}asc&order[]=field{order_split}asc
		d.order_split = "-";
		d.order = $_GET['order'] || [];
		// 搜索字段query规则： search=abc&search_field=field_name
		d.search = $_GET['search']||'';
		d.searchField = $_GET['search_field']||'';
		// 列表+选中
		d.list = {
			current_page : 1,
			data : [],
			last_page : 1,
			per_page : 1,
			total : 0
		};
		d.selectedIds = [];
		return d;
	},
	created : function(){
		this._sortReset();
	},
	methods : {
		_sortReset : function(){
			if(this.order instanceof Array){
				for(var i=0,l=this.order.length,temp=null;i<l;i++){
					temp = this.order[i].toLocaleLowerCase().split(this.order_split);
					if(temp[1] == 'asc'){
						this[temp[0]+'Asc'] = true;
					}else if(temp[1] == 'desc'){
						this[temp[0]+'Asc'] = false;
					}else{
						this[temp[0]+'Asc'] = null;
					}
				}
			}
		},
		sort : function(field){
			var self = this;
			self[field+'Asc'] = !self[field+'Asc'];

			var i,l,temp,fields=[];
			if($_GET['order'] instanceof Array){
				for(i=0,l=$_GET['order'].length;i<l;i++){
					temp = $_GET['order'][i].split(self.order_split);
					fields.push(temp[0]);
				}
			}else{
				$_GET['order'] = [];
			}
			var fieldIndex = $.inArray(field,fields);
			if( fieldIndex < 0 ){
				// 不在
				$_GET['order'].push(field+self.order_split+(self[field+'Asc']?'asc':'desc'));
			}else{
				$_GET['order'][fieldIndex] = field+self.order_split+(self[field+'Asc']?'asc':'desc');
			}
			// window.location.replace($_URL+$_GETSTRING());
			window.location.href = $_URL+$_GETSTRING();
		},
		changeListRows : function(){
			$_GET['page'] = 1;
			$_GET['per_page'] = this.list.per_page;
			// window.location.replace($_URL+$_GETSTRING());
			window.location.href = $_URL+$_GETSTRING();
		},
		searchTo : function(){
			$_GET['page'] = 1;
			$_GET['search'] = this.search;
			$_GET['search_field'] = this.searchField;
			// window.location.replace($_URL+$_GETSTRING());
			window.location.href = $_URL+$_GETSTRING();
		},
		delByIds : function(id){
			var self = this;
			bootbox.confirm({
				size : "small",
				title : "删除提示",
				message : "确定要删除？",
				buttons : {
					confirm : {
						label : '确定',
						className : 'btn btn-danger'
					},
					cancel : {
						label : '取消',
						className : 'btn btn-default'
					}
				},
				callback : function(res){
					// res is a boolean; true = OK, false = Cancel
					// console.log(res);
					if(res){
						// confirm
						var selectedIds = self.selectedIds.join(',');
						// 删除单个
						if(typeof id === 'string' || typeof id === 'number'){
							selectedIds = id;
						}
						if(!selectedIds){
							/**
							 * gritter 通知
							 * @param  object    config 配置
							 * @param  string    config.title 标题
							 * @param  string    config.text 内容
							 * @param  string    config.image 内容图片
							 * @param  boolean   config.sticky 是否固定(true-不会自动消失,false-过一段时间会消失)
							 * @param  int       config.time 消失时间
							 * @param  string    config.class_name 通知的样式类(['gritter-info','gritter-success','gritter-warning','gritter-error'],['gritter-light'],['gritter-center'])
							 * @param  callback  config.before_open 打开通知之前的回调，返回false不会打开
							 */
							// $.gritter.add(config);
							// $.gritter.removeAll();
							$.gritter.add({
								title : '删除提示',
								text : '未选中任何对象进行删除',
								sticky : false, // 是否固定(true-不会自动消失,false-过一段时间会消失)
								time : 3000,
								class_name : 'gritter-error'
							});
						}else{
							$.post(self.delUrl,{
								ids : selectedIds
							},function(res){
								if(res.code == 200){
									window.location.reload();
								}else{
									$.gritter.add({
										title : '删除失败提示',
										text : res.msg,
										sticky : false, // 是否固定(true-不会自动消失,false-过一段时间会消失)
										time : 3000,
										class_name : 'gritter-error'
									});
								}
							});
						}
					}else{
						// cancel
					}
				}
			});
		}
	},
	computed : {
		checkboxAll : {
			get : function(){
				var selectedIds = this.selectedIds;
				for(var i=selectedIds.length-1;i>=0;i--){
					if(!selectedIds[i]){
						selectedIds.splice(i, 1);
					}
				}
				if(this.list.total==0){
					// 如果一个元素没有
					return false;
				}
				// 原因：有可能总数 <= 第一页显示数量
				return selectedIds.length >= this.list.per_page || selectedIds.length >= this.list.total;
			},
			set : function(newVal){
				var list = this.list.data;
				if(newVal){
					this.selectedIds = [];
					for(var i=0,l=list.length;i<l;i++){
						this.selectedIds.push(list[i]['id']);
					}
				}else{
					this.selectedIds = [];
				}
			}
		}
	}
};